package com.mcxx.modules.miniSalvation.check.service.write;

import com.mcxx.common.exception.BizException;
import com.mcxx.convert.CheckConvert;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.filemanage.easypoi.util.ExportExcelService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.dao.read.CheckReadDao;
import com.mcxx.modules.miniSalvation.check.dao.write.CheckWriteDao;
import com.mcxx.modules.miniSalvation.check.dto.CheckListExcelDTO;
import com.mcxx.modules.miniSalvation.check.dto.DepartmentDataDTO;
import com.mcxx.modules.miniSalvation.check.entity.CheckEntity;
import com.mcxx.modules.miniSalvation.check.param.CheckListSearchParam;
import com.mcxx.modules.miniSalvation.order.dto.CheckDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.RecheckBatchWriteService;
import com.mcxx.modules.system.entity.TaskExportEntity;
import com.mcxx.modules.system.service.write.TaskExportWriteService;
import com.mcxx.util.BatchNoUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.component.audit.vo.ExcelInfo;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;


@Slf4j
@Service
@TaTransactional
public class CheckWriteService extends BaseService {

    @Autowired
    private CheckWriteDao checkWriteDao;
    @Autowired
    private CheckReadDao checkReadDao;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ExportExcelService exportExcelService;
    @Autowired
    private TaskExportWriteService taskExportWriteService;
    @Autowired
    private RecheckBatchWriteService recheckBatchWriteService;

    public static final String [] IntegrateAreaCode = {"430922","430923","430921"};

    public List<CheckEntity>  addCheck(List<CheckDTO> checkDTOList,String areaCode, String checkState, String checkType, String businessType) {


        String cityBatchNo = BatchNoUtil.getBatch(Constant.BusiCode.CHECK_BATCH, areaCode);


        String countyCode = areaCode.substring(0,6);
        String countryBatchNo="";
        if(Arrays.stream(CheckWriteService.IntegrateAreaCode).filter(o->o.equals(countyCode)).findAny().isPresent()){
            countryBatchNo = cityBatchNo;
        }else {
            countryBatchNo = BatchNoUtil.getNewBatch(cityBatchNo);
        }
        List<CheckEntity> checkEntityList = new ArrayList<>();
        CheckEntity checkEntity;

        for (CheckDTO checkDTO : checkDTOList) {
            String uuid = Constant.getUUID();
            checkDTO.setCheckId(uuid);
            checkDTO.setBusinessType(businessType);
            checkDTO.setCheckType(checkType);
            if(Constant.BusinessStandType.CITY_DIBAO.equals(checkDTO.getStandType())||Constant.BusinessStandType.CITY_TEKUN.equals(checkDTO.getStandType())){
                checkDTO.setCheckBatchNo(cityBatchNo);
                checkEntity = CheckConvert.convertCheckEntity(checkDTO, cityBatchNo, checkState, checkType);
            }else {

                checkDTO.setCheckBatchNo(countryBatchNo);
                checkEntity = CheckConvert.convertCheckEntity(checkDTO, countryBatchNo, checkState, checkType);
            }
            checkEntityList.add(checkEntity);
        }


        int rst = checkWriteDao.inserts(checkEntityList);
        if(rst <= 0){
            throw new BizException("-1", "保存核对信息失败");
        }
        return checkEntityList;
    }

    public List<CheckEntity> addDepartmentCheck(List<DepartmentDataDTO> departmentDataDTOS, String areaCode) {

        String batchNo = BatchNoUtil.getBatch(Constant.BusiCode.CHECK_BATCH, areaCode);

        List<CheckEntity> checkEntityList = new ArrayList<>();

        for (DepartmentDataDTO dataDTO : departmentDataDTOS) {
            CheckEntity entity = new CheckEntity();
            String uuid = Constant.getUUID();
            entity.setCheckId(uuid);
            entity.setOrderId(dataDTO.getId());
            entity.setFamilyId(dataDTO.getId());
            entity.setAreaCode(dataDTO.getAreaCode());
            entity.setIdcard(dataDTO.getIdcard());
            entity.setCheckState(Constant.CheckState.WIAT_SEND);
            entity.setCheckBatchNo(batchNo);
            entity.setBusinessType(Constant.CheckRequestType.OTHER);
            entity.setCheckType(Constant.OrderType.NEW);
            entity.setCreateTime(new Date());
            checkEntityList.add(entity);
        }

        int rst = checkWriteDao.inserts(checkEntityList);
        if(rst <= 0){
            throw new BizException("-1", "保存核对信息失败");
        }
        return checkEntityList;
    }

    public int addCheckNo(List<CheckDTO> checkDTOList,String batchNo, String checkState, String checkType) {


        Map<String, List<String>> rstMap = new HashMap<>();


        List<String> sendCheckIdCardList = new ArrayList<>();
        List<CheckEntity> checkEntityList = new ArrayList<>();
        CheckEntity checkEntity;

        for (CheckDTO checkDTO : checkDTOList) {

            checkEntity = CheckConvert.convertCheckEntity(checkDTO, batchNo, checkState, checkType);
            checkEntity.setCheckId(Constant.getUUID());


            checkEntityList.add(checkEntity);

            sendCheckIdCardList.add(checkDTO.getIdcard());
        }


        int rst = checkWriteDao.inserts(checkEntityList);
        if(rst <= 0){
            throw new BizException("-1", "保存核对信息失败");
        }
        return rst;
    }


    public int delete(CheckEntity orderCheck){
        return checkWriteDao.deleteEntity(orderCheck);
    }

    public int deleteIds(String areaCode,String[] ids,String [] status){
        return checkWriteDao.deleteIds(areaCode,ids,status);
    }


    public int   update(CheckEntity orderCheck){
        return  checkWriteDao.update(orderCheck);
    }


    public int   update(String[] batchNo, String status){
        return  checkWriteDao.updateStatus(batchNo,status);
    }


    public int updateIgnoreNull(CheckEntity orderCheck){
        return  checkWriteDao.updateIgnoreNull(orderCheck);
    }

    public int updateIgnoreNull(List<CheckEntity> param){
        int count = 0 ;
        for (int i = 0; i <param.size() ; i++) {
            count += checkWriteDao.updateIgnoreNull(param.get(i));
        }
        return count;
    }


    public int deleteBatch(String batchNo){
        return checkWriteDao.deleteBatch(batchNo);
    }


    public int updateCheckFileBatch(List<CheckEntity> entities){
        return checkWriteDao.updateCheckFileBatch(entities);
    }


    public int  updateCheckStateBatch(List<CheckEntity> list){
        return checkWriteDao.updateCheckStateBatch(list);
    }


    public int updateCheckMsgBatch(List<CheckEntity> list){
        return checkWriteDao.updateCheckMsgBatch(list);
   }


    public int updateCheckState(CheckEntity checkEntity){
        return checkWriteDao.updateCheckStateByEntity(checkEntity);
   }


    public int updateCheckByCheckId(CheckEntity checkEntity){
        return checkWriteDao.updateCheckByCheckId(checkEntity);
    }

    public int updateCheckStateById(List<String>idlist,String exceptionMsg,String checkState){
       return checkWriteDao.updateCheckStateById(idlist,exceptionMsg,checkState);
    }

    public int updateCheckStateByBatchNo(String batchNo,List<String> idsList,String exceptionMsg,String checkState){
        return checkWriteDao.updateCheckStateByBatchNo(batchNo,idsList,exceptionMsg,checkState);
    }

    public int uploadCheckFile(CheckEntity checkEntity,String[] filesKey){

        List<CheckEntity> entities = new ArrayList<>();
        if(filesKey==null||filesKey.length<1){
            throw new BizException("-1","没有核对文件");
        }
        try {

            //String batchNo = BatchNoUtil.getBatch(Constant.BusiCode.CHECK_BATCH, checkEntity.getAreaCode());

            int checkSeconds = 1;
            for(String key :filesKey){
                checkSeconds++;
                CheckEntity check  = new CheckEntity();
                Date date = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.add(Calendar.SECOND, checkSeconds);
                date = c.getTime();
                String uuid = Constant.getUUID();
                check.setCheckId(uuid);
                check.setOrderId(checkEntity.getOrderId());
                check.setFamilyId(checkEntity.getFamilyId());
                check.setBusinessType(checkEntity.getBusinessType());
                check.setCheckType(Constant.CheckType.NEW);
                check.setAreaCode(checkEntity.getAreaCode());
                check.setIdcard(checkEntity.getIdcard());

                check.setCheckState(Constant.CheckState.FORWARD_RESULT);
                check.setCheckResultState(checkEntity.getCheckResultState());
                check.setCheckBatchNo(checkEntity.getCheckBatchNo());
                check.setCheckReportNo(checkEntity.getCheckReportNo());
                check.setStandType(checkEntity.getStandType());
                check.setCheckReportFile(key);
                check.setReportTime(date);

                check.setShowFlag("3");
                check.setCheckRemark(checkEntity.getCheckRemark());
                check.setCreateTime(date);
                entities.add(check);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("核对文件上传失败");
            throw new BizException(FailureCode.ERR_20078);
        }
        int rst = checkWriteDao.inserts(entities);
        if(rst<=0){
            throw new BizException("-1","保存失败");
        }
        return rst;
    }


    @Deprecated
    public void completeCheck(List<String> orderIdList){
        for(String orderId : orderIdList){
            OrderEntity orderEntity = orderReadService.getById(orderId);



            int rst = checkWriteDao.updateCheckComplete(orderId);
            if(rst <= 0){
                throw new BizException("-1", orderEntity.getIdcard() + "完成核对失败");
            }
        }
    }
    public int deleteByOrderId(String orderId){
        return checkWriteDao.deleteByOrderId(orderId);
    }


    public int copyCheckInfo(String orderId,String newOrderId){
        return checkWriteDao.copyCheckInfo(orderId,newOrderId);
    }

   public String conferIntegrat(List<String> checkIds){
       if(null == checkIds || checkIds.size()==0){
           return "请选择核对数据";
       }
       int i = checkWriteDao.conferIntegratList(checkIds);
       recheckBatchWriteService.updateStateByCheckIds(checkIds);
       return "成功下发"+i+"条记录";
   }

    public ExcelInfo downLoadIntegrateCheckList(CheckListSearchParam param, UserAccountVo accountVo){

        QueryParamUtil.setBaseParamValue(param,accountVo);
        ExcelInfo excelInfo = null;
        List<CheckListExcelDTO> list = checkReadDao.exportIntegrateCheckList(param);
        excelInfo = exportExcelService.exportOrgOpLogs(CheckListExcelDTO.class,list,"核对家庭查询信息.xls",
                "核对家庭查询列表","核对家庭查询列表",false);

        return excelInfo;
    }
}
